const UserModel = require('../Model/UserModel')
const fs = require('fs');
const userModel = new UserModel()
class UserController {
    async add(req, res) {
        let { username, password } = req.body
        const userList = await userModel.check({ username })
        if (userList.length > 0) {
            if (password === userList[0].password) {
                let obj = {
                    code: 200,
                    data: {
                        title: '账号已存在，将直接登录',
                        type: 1
                    }
                }
                res.send(obj)
            } else {
                let obj = {
                    code: 200,
                    data: {
                        title: '密码错误',
                        type: 0
                    }
                }
                res.send(obj)
            }

        } else {
            await userModel.add({ username, password })
            let obj = {
                code: 200,
                data: {
                    title: '注册并登录成功',
                    type: 0
                }
            }
            res.send(obj)
        }


    }
    async findImg(req,res) {
        let { username } =req.query
        let imgObj = await userModel.findImg({ username })
        let obj = {
            code: 200,
            imgObj
        }
        res.send(obj)
    }
    async loadImg(req, res) {
        let { username } = req.query
        let userImg = req.files.file
        
        let readStream = fs.createReadStream(userImg.path); // 被复制文件
        // 创建一个写入流
        let writeStream = fs.createWriteStream('./public/images/' + userImg.name); // 复制到的目标位置及文件
        // 读取流的内容通过管道流写入到输出流
        readStream.pipe(writeStream);
        let path='http://localhost:3001/userimg'+writeStream.path.slice(writeStream.path.indexOf('/'))
        userImg.path=path
        let userList = await userModel.loadImg({ username, userImg })
        let obj = {
            code: 200,
            data: {
                userList
            }
        }
        res.send(obj)
    }
    async check(req, res) {
        let { username } = req.body
        const userList = await userModel.check({ username })
        let obj = {
            code: 200,
            data: {
                userList
            }
        }
        res.send(obj)
    }
}
module.exports = UserController